package com.dormitory_springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dormitory_springboot.bean.Admin;
import com.dormitory_springboot.bean.Dormitory;
import com.dormitory_springboot.form.Form;
import com.dormitory_springboot.form.FormInline;
import com.dormitory_springboot.form.RuleForm;
import com.dormitory_springboot.mapper.AdminMapper;
import com.dormitory_springboot.mapper.DormitoryMapper;
import com.dormitory_springboot.service.AdminService;
import com.dormitory_springboot.utils.JWTutil;
import com.dormitory_springboot.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @auther 夏杨
 **/
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    DormitoryMapper dormitoryMapper;
    public ResultVO login(RuleForm ruleForm){
        Admin admin = adminMapper.selectById(ruleForm.getId());
        ResultVO resultVO = new ResultVO();
        if(admin == null)
            resultVO.setCode(-1);
        else if(!admin.getPassword().equals(ruleForm.getPass())){
            resultVO.setCode(-2);
        }else {
            resultVO.setCode(0);
            resultVO.setData(admin);
            resultVO.setToken(JWTutil.creatJWTByAdimin(admin));
        }
        return resultVO;
    }

    @Override
    public List<Integer> check() {
        List<Dormitory> dormitories = dormitoryMapper.selectList(null);
        List<Integer> build = new ArrayList<>();
        dormitories.forEach(dormitory -> {
            if(!build.contains(dormitory.getBuilding())){
                build.add(dormitory.getBuilding());
            }
        });
        return build;
    }

    @Override
    public boolean adddormitory(Form form) {
        Dormitory dormitory = new Dormitory();
        for(int i=1;i<=form.getFloor();i++){
            for(int j=1;j<=form.getRoom();j++){
                if(j<10) {
                    dormitory.setDorid(form.getBuilding() + "#" + i + "0" + j);
                }else dormitory.setDorid(form.getBuilding() + "#" + i + j);
                dormitory.setBuilding(form.getBuilding());
                dormitoryMapper.insert(dormitory);
            }
        }
        return true;
    }

    @Override
    public List<Dormitory> getdormitory(FormInline formInline) {
        QueryWrapper<Dormitory> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(true, "dorid",formInline.getBuilding()+"#"+formInline.getFloor());
        List<Dormitory> dormitories = dormitoryMapper.selectList(queryWrapper);
        return  dormitories;
    }
}
